package com.zyw.module.console.admin.auth;

import com.zyw.module.console.user.po.User;
import com.zyw.module.console.user.service.UserService;
import com.zyw.security.shiro.web.authc.AuthInfo;
import com.zyw.security.shiro.web.authc.AuthService;
import com.zyw.utils.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author zhangyw
 * @date 2018/1/25 11:05
 */
@Component
public class SmsAuthService implements AuthService {
    private static final String LOGIN_SMSCODE_ATTRKEY = "login_sms_code";

    @Autowired
    private UserService userService;

    @Override
    public String getCredentials(Object principal) {
        Object smsCode = SecurityUtils.getSubject().getSession().getAttribute(LOGIN_SMSCODE_ATTRKEY);
        return (String) smsCode;
    }

    @Override
    public AuthInfo getAuthInfo(Object principal) {
        List<User> users = userService.findByPhone((String) principal);
        if (users != null && !users.isEmpty()) {
            AuthInfo authInfo = new AuthInfo();
            User user = users.get(0);
            authInfo.setUserid(user.getId());
            authInfo.setUsername(user.getUsername());
            authInfo.setPassword(user.getPassword());
            authInfo.setStatus(user.getStatus());
            return authInfo;
        }
        return null;
    }

    @Override
    public boolean validCredentials(String principal, String targetCredentials, String sourceCredentials) {

        if (StringUtils.isEmpty(sourceCredentials)) {
            sourceCredentials = getCredentials(principal);
        }

        boolean e = StringUtils.equals(targetCredentials, sourceCredentials);

        if (e) {// 验证通过，清除session中的验证码信息
            SecurityUtils.getSubject().getSession().removeAttribute(LOGIN_SMSCODE_ATTRKEY);
        }

        return e;
    }

    /**
     * 发送登录短信验证码
     * <p>
     * TODO 生成验证码策略，以及发送验证码给用户
     *
     * @param phone 手机号
     */
    public void sendLoginSmsCode(String phone) {
        SecurityUtils.getSubject().getSession().setAttribute(LOGIN_SMSCODE_ATTRKEY, "123456");
    }
}
